import React, { useEffect, useState } from 'react'
import { Avatar, Button, Card, List } from 'antd-mobile'
import {
    StarFill, TeamFill, VideoOutline, SetOutline, FileOutline,
    ContentOutline, PayCircleOutline, HeartFill, QuestionCircleOutline,
    AudioOutline, TextOutline, EditSFill
} from 'antd-mobile-icons'
import style from './my.module.css'
import { useNavigate } from 'react-router-dom'
import request from '../../../api/request'

function Index() {
    const nav = useNavigate()

    // 签到相关状态
    const [signedToday, setSignedToday] = useState(false)
    const [signDays, setSignDays] = useState(0)
    const [signLoading, setSignLoading] = useState(false)
    const [weeklySignStatus, setWeeklySignStatus] = useState([])

    // 生成最近一周的日期
    const generateWeekDates = () => {
        const dates = []
        const today = new Date()
        
        for (let i = 6; i >= 0; i--) {
            const date = new Date(today)
            date.setDate(today.getDate() - i)
            const dateKey = date.toISOString().split('T')[0] // YYYY-MM-DD 格式
            
            dates.push({
                date: date,
                dateKey: dateKey,
                day: date.getDate(),
                weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()],
                isToday: i === 0,
                isSigned: false
            })
        }
        return dates
    }

    // 从本地存储获取签到历史
    const getSignHistory = () => {
        try {
            const history = localStorage.getItem('signHistory')
            return history ? JSON.parse(history) : {}
        } catch {
            return {}
        }
    }

    // 保存签到历史到本地存储
    const saveSignHistory = (dateKey) => {
        try {
            const history = getSignHistory()
            history[dateKey] = true
            localStorage.setItem('signHistory', JSON.stringify(history))
        } catch (e) {
            console.error('保存签到历史失败:', e)
        }
    }

    const loadSignInfo = async () => {
        try {
            const resToday = await request.get('/user/verify/v1/whetherSignToday')
            const today = (resToday?.data?.result || 2) === 1
            setSignedToday(today)
            
            const resDays = await request.get('/user/verify/v1/findUserSign')
            setSignDays(Number(resDays?.data?.result || 0))
            
            // 生成周日期并加载本地签到历史
            const weekDates = generateWeekDates()
            const signHistory = getSignHistory()
            
            // 更新签到状态：今天根据API，其他日期根据本地存储
            weekDates.forEach(item => {
                if (item.isToday) {
                    item.isSigned = today
                    // 如果今天已签到，保存到本地存储
                    if (today) {
                        saveSignHistory(item.dateKey)
                    }
                } else {
                    item.isSigned = signHistory[item.dateKey] || false
                }
            })
            
            setWeeklySignStatus(weekDates)
        } catch (error) {
            console.error(error)
        }
    }

    useEffect(() => {
        loadSignInfo()
    }, [])

    const handleSign = async () => {
        if (signedToday || signLoading) return
        setSignLoading(true)
        try {
            await request.post('/user/verify/v1/addSign')
            setSignedToday(true)
            setSignDays((d) => Number(d || 0) + 1)
            
            // 更新今天的签到状态并保存到本地存储
            const today = new Date()
            const todayKey = today.toISOString().split('T')[0]
            saveSignHistory(todayKey)
            
            setWeeklySignStatus(prev =>
                prev.map(item =>
                    item.isToday ? { ...item, isSigned: true } : item
                )
            )
        } catch (error) {
            console.error(error)
        } finally {
            setSignLoading(false)
        }
    }

    return (
        <div className={style.box}>
            {/* 头部 */}
            <div className={style.loginTop}>
                <Avatar src={localStorage.getItem('touxiang')} style={{ '--size': '52px', borderRadius: '50px' }} />
                <h4>{localStorage.getItem('username') ? localStorage.getItem('username') : <div onClick={() => nav('/login')}>登录</div>}</h4>
            </div>

            {/* 会员 */}
            <div className={style.hengfu}>
                <span><StarFill /></span>
                <p style={{ fontSize: '14px' }}>不限次视频咨询，10秒接通</p>
                <Button size='mini' shape='rounded' style={{ background: '#ebc17f' }}>
                    立即开通
                </Button>
            </div>

            {/* 签到区域 */}
            <Card style={{ margin: '15px' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '15px' }}>
                    <div>
                        <h4 style={{ margin: 0, fontSize: '16px' }}>每日签到</h4>
                        <p style={{ margin: '5px 0 0 0', fontSize: '12px', color: '#666' }}>
                            已连续签到 {signDays} 天
                        </p>
                    </div>
                    <Button
                        size='small'
                        color='primary'
                        disabled={signedToday || signLoading}
                        onClick={handleSign}
                    >
                        {signedToday ? '已签到' : '签到'}
                    </Button>
                </div>

                {/* 周签到日历 */}
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: '8px' }}>
                    {weeklySignStatus.map((item, index) => (
                        <div
                            key={index}
                            style={{
                                flex: 1,
                                textAlign: 'center',
                                padding: '8px 4px',
                                borderRadius: '8px',
                                backgroundColor: item.isSigned ? '#e6f7ff' : '#f5f5f5',
                                border: item.isToday ? '2px solid #1890ff' : '1px solid #e8e8e8',
                                position: 'relative'
                            }}
                            title={`${item.weekday} ${item.date.getMonth() + 1}/${item.date.getDate()}${item.isSigned ? ' - 已签到' : ' - 未签到'}`}
                        >
                            <div style={{
                                fontSize: '12px',
                                color: '#666',
                                marginBottom: '4px'
                            }}>
                                {item.weekday}
                            </div>
                            <div style={{
                                fontSize: '16px',
                                fontWeight: 'bold',
                                color: item.isSigned ? '#1890ff' : '#333'
                            }}>
                                {item.day}
                            </div>
                            {item.isSigned && (
                                <div style={{
                                    position: 'absolute',
                                    top: '2px',
                                    right: '2px',
                                    width: '8px',
                                    height: '8px',
                                    borderRadius: '50%',
                                    backgroundColor: '#52c41a'
                                }} />
                            )}
                        </div>
                    ))}
                </div>
            </Card>

            {/* 我的收藏 */}
            <Card title='我的收藏' style={{ margin: '15px' }}>
                <div className={style.soucang}>
                    <div className={style.iconbox} onClick={() => nav('/followDoctor')}>
                        <TeamFill style={{ fontSize: '30px', color: '#fe8171' }} />
                        <div className={style.title}>医生</div>
                    </div>
                    <div className={style.iconbox}>
                        <VideoOutline style={{ fontSize: '30px', color: '#fe8171' }} />
                        <div className={style.title}>直播</div>
                    </div>
                    <div className={style.iconbox}>
                        <FileOutline style={{ fontSize: '30px', color: '#fe8171' }} />
                        <div className={style.title}>科普</div>
                    </div>
                    <div className={style.iconbox}>
                        <ContentOutline style={{ fontSize: '30px', color: '#fe8171' }} />
                        <div className={style.title}>帖子</div>
                    </div>
                </div>
            </Card>
            {/* 列表 */}
            <Card style={{ margin: '15px' }}>
                <List>
                    <List.Item description='关注健康 争做健康中国人' prefix={<HeartFill />} onClick={() => { }}>
                        健康值
                    </List.Item>
                    <List.Item prefix={<PayCircleOutline />} onClick={() => { }}>
                        健康步数
                    </List.Item>
                    <List.Item prefix={<QuestionCircleOutline />} onClick={() => { }}>
                        提问
                    </List.Item>
                    <List.Item prefix={<AudioOutline />} onClick={() => { }}>
                        已购医生咨询服务
                    </List.Item>
                    <List.Item prefix={<TextOutline />} onClick={() => { }}>
                        优惠劵
                    </List.Item>
                    <List.Item prefix={<EditSFill />} onClick={() => { }}>
                        意见反馈
                    </List.Item>
                    <List.Item prefix={<SetOutline />} onClick={() => { nav('/userset') }}>
                        系统设置
                    </List.Item>
                </List>
            </ Card>
        </div>
    )
}

export default Index
